package com.superjson.showpro.shared.exception;

import com.alibaba.fastjson.JSONObject;
import com.beantools.constants.SingleChar;
import com.superjson.showpro.shared.result.ErrorContext;
import com.superjson.showpro.shared.result.Result;
import com.superjson.showpro.shared.result.ResultCodeEnum;
import com.superjson.showpro.shared.util.LogUtil;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * Created By zby on 15:46 2019/6/21
 * <p>
 * 统一异常处理
 */

public class GeneralBizExceptionResolver implements HandlerExceptionResolver {

    private org.slf4j.Logger logger = LoggerFactory.getLogger(GeneralBizExceptionResolver.class);

    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object o, Exception e) {
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter writer = null;
        try {
            writer = response.getWriter();
        } catch (IOException e1) {
            LogUtil.error(logger, e1);
        }
        Result result = new Result();
        result.setSuccess(false);
        GeneralBizException ge = e instanceof GeneralBizException ? (GeneralBizException) e : new GeneralBizException(ResultCodeEnum.UNKNOWN_EXCEPTION);
        LogUtil.error(logger, ge);
        result.setErrorCtx(new ErrorContext(ge.getErrCode(), ge.getErrMsg()));
        result.setResultData(SingleChar.NULL);
        writer.write(JSONObject.toJSONString(result));
        writer.flush();
        writer.close();
        return null;
    }
}
